from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
import logging
import os
from sqlalchemy.engine import Engine
from config import config

db = SQLAlchemy()
bcrypt = Bcrypt()
login_manager = LoginManager()

def create_app(config_name=None):
    if config_name is None:
        config_name = os.getenv('FLASK_CONFIG', 'default')

    app = Flask(__name__)
    app.config.from_object(config[config_name])

    # 根据环境设置日志级别
    if app.config['ENV'] == 'production':
        logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING)
    else:
        logging.basicConfig()
        logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    # 设置数据库连接池
    app.config['SQLALCHEMY_ENGINE_OPTIONS'] = {
        'pool_size': 10,
        'pool_timeout': 30,
        'pool_recycle': 1800,
    }

    db.init_app(app)
    bcrypt.init_app(app)
    login_manager.init_app(app)

    from . import routes
    app.register_blueprint(routes.main_bp)

    return app